package service

import (
	"context"
	"errors"
	appsv1 "k8s.io/api/apps/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"log"
)

type statefulset struct {}

var Statefulset statefulset

//定义列表的返回内容 Item是deploy元素列表  Total为元素数量
type StatefulsetResp struct {
	Item  []appsv1.StatefulSet `json:"item"`
	Total int                 `json:"total"`
}

//类型转换方法 appsv1.StatefulSet -> DataCell
func (s *statefulset) toCell(statefulsets []appsv1.StatefulSet) []DataCell {
	cell := make([]DataCell, len(statefulsets))
	for i := range statefulsets {
		cell[i] = statefulsetCell(statefulsets[i])
	}
	return cell
}

//类型转换方法  DataCell -> appsv1.DaemonSet
func (s *statefulset) fromCells(cells []DataCell) []appsv1.StatefulSet {
	statefulsets := make([]appsv1.StatefulSet, len(cells))
	for i := range cells {
		// cells[i].(deploymentCell) 类型转换
		statefulsets[i] = appsv1.StatefulSet(cells[i].(statefulsetCell))

	}
	return statefulsets
}

//获取deploy列表 支持过滤 排序 分页
func (s *statefulset) GetStatefulsets(filtername, namespacen string, limit, page int) (statefulsetResp *StatefulsetResp, err error) {
	//获取deploymentList类型的deploy列表
	statefulsetList, err := K8s.ClientSet.AppsV1().StatefulSets(namespacen).List(context.TODO(), metav1.ListOptions{})
	if err != nil {
		log.Printf("[ Deployment ]资源列表获取失败：%s", err)
		return nil, errors.New("获取Deployment列表失败" + err.Error())
	}

	selectableData := &dataSelector{
		GenericDataList: s.toCell(statefulsetList.Items),
		DataSelectQuery: &DataSelectQuery{
			FilterQuery: &FilterQuery{Name: filtername},
			PaginateQuary: &PaginateQuary{
				Limit: limit,
				Page:  page,
			},
		},
	}

	//先过滤
	filtered := selectableData.Filter()
	total := len(filtered.GenericDataList)
	//先排序再分页
	data := filtered.Sort().Paginate()

	statefulsets := s.fromCells(data.GenericDataList)

	return &StatefulsetResp{
		Total: total,
		Item:  statefulsets,
	}, nil

}

//获取 statefulset 详情
func (s *statefulset) GetStatefulDetail(statefulName, namespace string) (statefulset *appsv1.StatefulSet, err error) {

	statefulset, err = K8s.ClientSet.AppsV1().StatefulSets(namespace).Get(context.TODO(), statefulName, metav1.GetOptions{})
	if err != nil {
		log.Printf("获取statefulset详情失败：%s", err)
		return nil, errors.New("获取[statefulset]详情失败: %s" + err.Error())
	}
	return statefulset, nil
}

//删除 statefulset
func (s *statefulset)DelStatefulset(statefulName, namespace string) error {
	err := K8s.ClientSet.AppsV1().StatefulSets(namespace).Delete(context.TODO(),statefulName,metav1.DeleteOptions{})
	if err != nil {
		log.Printf("删除 statefulset 详情失败：%s", err)
		return  errors.New("删除 statefulset 详情失败：%s" + err.Error())
	}
	return nil
}



